//
//  UIView+Loading.m
//  HappyonlineUser
//
//  Created by admin on 2017/3/22.
//  Copyright © 2017年 肖世恒. All rights reserved.
//

#import "UIView+Loading.h"

@implementation UIView (Loading)

#pragma mark ----------------加载方法------------------------
- (void)showLoadingWithView{
    
    
    if ([self isKindOfClass:[UITableView class]]) {
        
        UITableView *tableView = (UITableView *)self;
        if(!tableView.mj_header.isRefreshing && !tableView.mj_footer.isRefreshing){
            
            ///开始用 内加载
            [self loadNoDataViewhidden:Loading_TYPE_DATA];
            
        }
    
    }else if ([self isKindOfClass:[UICollectionView class]]) {
        UICollectionView *collectionView = (UICollectionView *)self;
    
        if(!collectionView.mj_header.isRefreshing && !collectionView.mj_footer.isRefreshing){
            
            ///开始用 内加载
            [self loadNoDataViewhidden:Loading_TYPE_DATA];
            
        }
    }else{
        ///开始用 内加载
        [self loadNoDataViewhidden:Loading_TYPE_DATA];
    }
    
}

/**
 关闭
 
 @param title 提示文字   （如果填写就会以HUD方式 显示出来）
 @param beData 是否有数据
 */
- (void)hiddenLoadingWithTitle:(NSString*)title beData:(BOOL)beData{
    
    if ([self isKindOfClass:[UITableView class]]) {
        

            UITableView *tableView = (UITableView *)self;
        
            [tableView.mj_header endRefreshing];
            [tableView.mj_footer endRefreshing];
            
        
        
    }else if ([self isKindOfClass:[UICollectionView class]]) {
        UICollectionView *collectionView = (UICollectionView *)self;
        
   
            
            [collectionView.mj_header endRefreshing];
            [collectionView.mj_footer endRefreshing];
            
        
    }

    if (beData) {
        [self loadNoDataViewhidden:Loading_TYPE_YES];
    }else{
        [self loadNoDataViewhidden:Loading_TYPE_NO_DATA];
    }
    ///没有字符 不用执行
    if (![NSString isBlankString:title]) {
        
        [XBProgressHUD showProgressHUDWithText:title];
        
    }
    
    
    
}

/**
 错误
 @param title 提示
 */
- (void)errorLoadingWithTitle:(NSString*)title{
    
    
    if ([self isKindOfClass:[UITableView class]]) {
        
        UITableView *tableView = (UITableView *)self;
    
        [tableView.mj_header endRefreshing];
        [tableView.mj_footer endRefreshing];
        [tableView reloadData];
        
        
        
    }else if ([self isKindOfClass:[UICollectionView class]]) {
        UICollectionView *collectionView = (UICollectionView *)self;
        
        [collectionView.mj_header endRefreshing];
        [collectionView.mj_footer endRefreshing];
        [collectionView reloadData];
 
    }
    
    BOOL successful = [self loadNoDataViewhidden:Loading_TYPE_NO_NETWORK];
    
    ///没有执行成功 弹出 提示
    if(!successful){
        
        [XBProgressHUD showProgressHUDWithText:title];
    }
    
    
}

#pragma mark - noDataView--------
static const char noLoadingViewKey = '\0';
static char delegateLoadingKey;


- (void)setLoadingView:(XBLoading *)LoadingView{
    
    
    if (LoadingView != self.LoadingView) {
        // 删除旧的，添加新的
        [self.LoadingView removeFromSuperview];
        
//        [self insertSubview:LoadingView atIndex:0];
        [self bringSubviewToFront:LoadingView];
        
        // 存储新的
        [self willChangeValueForKey:@"noLoadingViewKey"]; // KVO
        objc_setAssociatedObject(self, &noLoadingViewKey,
                                 LoadingView, OBJC_ASSOCIATION_ASSIGN);
        [self didChangeValueForKey:@"noLoadingViewKey"]; // KVO
    }
    
    
}

- (XBLoading *)LoadingView{
    
    return objc_getAssociatedObject(self, &noLoadingViewKey);
    
}

- (void)setDelegateLoading:(id<UIViewLoadingDelegate>)delegateLoading{
    
    if (delegateLoading != self.delegateLoading) {
        
        self.delegateLoading = nil;
        // 存储新的
        [self willChangeValueForKey:@"delegateLoadingKey"]; // KVO
        objc_setAssociatedObject(self, &delegateLoadingKey,
                                 delegateLoading, OBJC_ASSOCIATION_ASSIGN);
        [self didChangeValueForKey:@"delegateLoadingKey"]; // KVO
    }
    
}


- (id<UIViewLoadingDelegate>)delegateLoading{
    return objc_getAssociatedObject(self, &delegateLoadingKey);
}


#pragma mark ----------------为view自动添加加载数据控件------------------------

- (BOOL)loadNoDataViewhidden:(Loading_TYPE)Type {
    
    if (!self.LoadingView) {
        self.LoadingView = [self setloadingView];
        self.LoadingView.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        [self addSubview:self.LoadingView];
    }
    if(Type == Loading_TYPE_DATA){
        
        if ([self isKindOfClass:[UITableView class]] ||[self isKindOfClass:[UICollectionView class]])  {
        
            if([self totalDataCount] <= 0){
                
                [self showException:Type];
                
                return YES;
            }else{
                
                self.LoadingView.hidden = YES;
                [self hideException];
                return NO;
            }
        
        }else{
            
            [self showException:Type];
            
            return YES;
        }
        
    }else if(Type == Loading_TYPE_NO_DATA){
        
        [self showException:Type];
        
        return YES;
        
    }else if(Type == Loading_TYPE_NO_NETWORK){
        
        [self showException:Type];
        
        return YES;
        
    }else{
        
        [self showException:Type];
        
        return YES;
        ///成功
    }


}
- (NSInteger)totalDataCount
{
    NSInteger totalCount = 0;
    if ([self isKindOfClass:[UITableView class]]) {
        UITableView *tableView = (UITableView *)self;
        
        for (NSInteger section = 0; section<tableView.numberOfSections; section++) {
            totalCount += [tableView numberOfRowsInSection:section];
        }
    } else if ([self isKindOfClass:[UICollectionView class]]) {
        UICollectionView *collectionView = (UICollectionView *)self;
        
        for (NSInteger section = 0; section<collectionView.numberOfSections; section++) {
            totalCount += [collectionView numberOfItemsInSection:section];
        }
    }
    return totalCount;
}


#pragma mark -
#pragma mark - 异常处理、如提示无网络，或者无数据等等
-(XBLoading *)setloadingView{
    
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"XBLoading" owner:nil options:nil];
    
    XBLoading *loadingView = [views firstObject];
    [loadingView addTarget:self action:@selector(reloadDataForException) forControlEvents:UIControlEventTouchDown];
    
    return loadingView;
    
}

-(void)hideException{
    
    if (self.LoadingView) {
        [self.LoadingView removeFromSuperview];
        self.LoadingView = nil;
        
    }
}

-(void)showException:(Loading_TYPE)exceptionType{
    
    
    
    if(exceptionType == Loading_TYPE_YES){
        
        self.LoadingView.hidden = YES;
        [self hideException];
    }
    
    [self.LoadingView setupException:exceptionType];
    
}

-(void)reloadDataForException{
    
    //判断是不是处理中
    if (self.LoadingView.isHandleException) {
        
        DLog(@"正在处理...");
        return;
    }
    if (self.delegateLoading && [self.delegateLoading respondsToSelector:@selector(updateRequest)]) {
        
        [self.delegateLoading updateRequest];
        
    }else{
        DLog(@"请实现协议updateRequest方法添加刷新");
    }

}

@end
